var express = require('express');
var router = express.Router();
var dbUtil = require('../modules/dbUtil');

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Database Config' });
});

router.post('/initdb', function(req, res, next) {
  var param = JSON.stringify(req.body);
  var dbutil = new dbUtil();
  var conn = dbutil.init(req.body);
  if(conn == null){
    res.render('error', {
      message: 'Config Params Error.',
      error: param
    });
  }else {
    dbutil.connect(conn, function (result) {
      if (result == -1) {
        res.render('error', {
          message: 'DB Connect Fail.',
          error: param
        });
      } else {
        dbutil.initDB(conn, 'cms_test', function (result) {
          if (result == -1) {
            res.render('error', {
              message: 'Database Create Fail.',
              error: param
            });
          } else if (result == -2) {
            res.render('error', {
              message: 'DB Table Create Fail.',
              error: param
            });
          } else {
            res.render('database', {title: 'Database Config', message: 'SUCCESS'})
          }
        });
      }
    });
  }

});

module.exports = router;
